package com.naiterui.ehp.bp.security.properties;

import cn.hutool.captcha.AbstractCaptcha;
import cn.hutool.captcha.CaptchaUtil;
import cn.hutool.captcha.ShearCaptcha;
import cn.hutool.captcha.generator.MathGenerator;
import cn.hutool.captcha.generator.RandomGenerator;
import com.naiterui.ehp.bp.security.exception.BadConfigurationException;
import java.awt.Font;
import java.util.Objects;
import lombok.Data;
import org.apache.commons.lang3.StringUtils;
import org.springframework.boot.context.properties.ConfigurationProperties;

/**
 * 配置文件读取
 */
@Data
@ConfigurationProperties(prefix = "login")
public class LoginProperties {

  /**
   * 账号单用户 登录
   */
  private boolean singleLogin = false;

  private LoginCodeProperties loginCode = new LoginCodeProperties();
  /**
   * 用户登录信息缓存
   */
  private boolean cacheEnable = true;

  /**
   * 获取验证码生产类
   *
   * @return /
   */
  public AbstractCaptcha getCaptcha() {
    if (Objects.isNull(this.loginCode)) {
      if (Objects.isNull(this.loginCode.getCodeType())) {
        this.loginCode.setCodeType(LoginCodeEnum.ARITHMETIC);
      }
    }
    return this.switchCaptcha(this.loginCode);
  }

  public boolean verify(String code, String userInputCode) {
    switch (this.loginCode.getCodeType()) {
      case ARITHMETIC:
        MathGenerator mathGenerator = new MathGenerator(1);
        return mathGenerator.verify(code, userInputCode);
      case RANDOM:
        return code.equalsIgnoreCase(userInputCode);
      default:
        throw new BadConfigurationException("验证码配置信息错误！正确配置查看 LoginCodeEnum ");
    }
  }

  /**
   * 依据配置信息生产验证码
   *
   * @param loginCodeProperties 验证码配置信息
   * @return /
   */
  private AbstractCaptcha switchCaptcha(LoginCodeProperties loginCodeProperties) {
    ShearCaptcha captcha = CaptchaUtil
        .createShearCaptcha(loginCodeProperties.getWidth(), loginCodeProperties.getHeight(), loginCodeProperties.getLength(), 3);
    // 自定义验证码内容为四则运算方式
    captcha.setGenerator(new MathGenerator(1));
    synchronized (this) {
      switch (loginCodeProperties.getCodeType()) {
        case ARITHMETIC:
          // 几位数运算，默认是两位
          captcha.setGenerator(new MathGenerator(1));
          break;
        case RANDOM:
          captcha.setGenerator(new RandomGenerator(4));
          break;
        default:
          throw new BadConfigurationException("验证码配置信息错误！正确配置查看 LoginCodeEnum ");
      }
    }
    if (StringUtils.isNotBlank(loginCodeProperties.getFontName())) {
      captcha.setFont(new Font(loginCodeProperties.getFontName(), Font.PLAIN, loginCodeProperties.getFontSize()));
    }
    return captcha;
  }

}
